import React, { Component } from 'react';
import classnames from 'classnames';
import { observer, inject } from 'mobx-react';
import { toJS } from 'mobx';
import { withRouter, Route } from 'react-router-dom';
import { Tools, Avatar, Icon, Result, Toast, List, PhotoSwipe, Modal, Bubble  } from 'weaver-mobile';
import { RouteLayout, ListPage } from 'weaver-mobile-page';
import { renderLoading } from '../../util';
import ContentIframe from './ContentIframe';
import FilePreview from '../attachment/filePreview';
import StaticReadList from './StaticReadList';

const { getWeaverFile, getLabel } = Tools;

@inject('viewStore')
@withRouter
@observer
class StaticView extends Component {
  static defaultProps = {
    prefixCls: 'email-static-view',
  }

  constructor(props) {
    super(props);
    this.state = {
      file: {} // 附件预览的file
    }
  }

  componentWillMount() {
    let { match: { url, params: { id } }, viewStore: { staticViewStore } } = this.props;
    staticViewStore.setStoreState({path: url})
    staticViewStore.getViewRight({mailId: id})
  }

  componentDidMount() {
    let viewport = document.querySelector("meta[name=viewport]");
    viewport.setAttribute('content', "width=device-width,initial-scale=1,maximum-scale=10,minimum-scale=1,user-scalable=yes");
  }

  componentWillReceiveProps(nextProps) {
    let { match: { params: { id: _id } }, viewStore: { staticViewStore } } = this.props;
    const { match: { url, params: { id }} } = nextProps;
    if (id && _id !== id) {
      staticViewStore.setStoreState({path: url})
      staticViewStore.getViewRight({mailId: id})
    }
  }

  componentWillUnmount() {
    let { viewStore: { staticViewStore } } = this.props;
    staticViewStore.clear();
    // 取消浏览器缩放支持
    let viewport = document.querySelector("meta[name=viewport]");
    viewport.setAttribute('content', "width=device-width,initial-scale=1,maximum-scale=10,minimum-scale=1,user-scalable=no");
  }

  onReadListClick = () => {
    const { history, viewStore: { staticViewStore } } = this.props;
    const { path, getReadList } = staticViewStore;
    getReadList();
    history.push(`${path}/readList`);
  }

  hasBeyondLen = (data) => {
    return data && data.length > 5;
  }

  replaceContent = (content) => {
    const res = /<a([\s]+|[\s]+[^<>]+[\s]+)href=(\"([^<>"\']*)\"|\'([^<>"\']*)\')[^<>]*>/gi; // 查找a标签；
    const hrefRes = /href="([^"]*)"/gi;
    let newContent = content;
    newContent = newContent.replace(res, m => {
      if (m.indexOf('common/chatResource/emailURL.html') !== -1) {
        return m.replace(hrefRes, n => `${n.slice(0,n.length-1)}&em_client_type=mobile"`)
      } else {
        return m
      }
    })
    return newContent;
  }

  scrollToEnclousure() { // 点击附件滚动到指定位置
    const files = document.getElementById('files');
    const content = document.getElementById('content');
    const offsetTop = files.offsetTop
    content.scrollTop = offsetTop;
  }

  doFilePreview = (file) => {
    const { history, viewStore: { baseInfo,staticViewStore } } = this.props;
    const { prohibitDownload,unPreview } = toJS(baseInfo);
    const isiPhone = Tools.mobileDetect().is('iPhone');
    const isEmobile = Tools.mobileDetect().isEmobile();
    this.setState({ file });
    const { isImg, isCanPreviewForMobile, filelink } = file;
    if("1" == unPreview){
      //禁止预览
      if("1" == prohibitDownload){
        //后台【禁止附件预览】和【禁止移动端下载】同时关闭时，点击附件时需要有提示
        Bubble.warning(getLabel('520701','系统设置原因，该文件只能在PC端下载查看'), 2);
        return;
      }else{
        this.curentModal = Modal.alert(getLabel('520702','后台邮件系统设置,禁止附件预览'), getLabel('514233','是否下载？'), [
          { text: getLabel('31129', '取消') },
          { text: getLabel('826', '确定'), onPress: () => {
            if (isiPhone && !isEmobile) {
              window.open(filelink+"&_ec_ismobile=true&ddcode="+file.ddcode);
            } else {
              getWeaverFile(filelink+"&_ec_ismobile=true&ddcode="+file.ddcode, 'iframe','email');
            }
          }},
        ])
      }
    }else{
      if (isImg !== 'true' && isCanPreviewForMobile !== 'true') {
        if("1" == prohibitDownload){
          //若因文件本身的问题不能预览，移动端也不能下载时，点击附件时需要有提示
          Bubble.warning(getLabel('520703','文件格式等原因，该文件只能在PC端下载查看'), 2);
          return;
        }else{
          this.curentModal = Modal.alert(getLabel('514232','当前文件不可预览') , getLabel('514233','是否下载？'), [
            { text: getLabel('31129', '取消') },
            { text: getLabel('826', '确定'), onPress: () => {
              if (isiPhone && !isEmobile) {
                window.open(filelink+"&_ec_ismobile=true&ddcode="+file.ddcode);
              } else {
                getWeaverFile(filelink+"&_ec_ismobile=true&ddcode="+file.ddcode, 'iframe','email');
              }
            }},
          ])
        }
      } else {
      history.push(`${staticViewStore.path}/preview`);
      }
    }
  }

  iframState = (val) => {
    const { viewStore: { staticViewStore } } = this.props;
    staticViewStore.setStoreState({iframeLoading: val})
    !val && Toast.hide();
  }
  
  getToItem = (name, datas) => { // isShowBcc: 是否邮件的秘送人
    const { prefixCls } = this.props;
    const cls = `${prefixCls}-complete-to-item`;
    if (datas.length === 0) return null;
    const curDatas = datas.length > 5 ? datas.slice(0, 5) : datas;
    return (
      <div className={cls}>
        <span className={`${cls}-title`}>{name}</span>
        <div className={`${cls}-detail`}>
          {curDatas.map((d, index) => (
            <span className={`${cls}-detail-unread`} key={`baseTo${index}`}>
              <a className={`${cls}-detail-name`} style={d.isInternal === 1 && d.type ==='resource' ? {color:'#55B1F9'}:{}} onClick={() =>  d && d.isInternal === 1 && d.type ==='resource' && this.openHrmCard(d.typeValue)}>{d.showName}</a>
            </span>
          ))}
          {datas.length > 5 && <span>...</span>}
        </div>
      </div>
    );
  }

  openHrmCard = (id) => {
    if (window.em && (typeof window.em.checkJsApi === 'function') && window.em.checkJsApi('openLink')) {
      window.em.openLink({
        url: `/spa/hrm/static4mobile/index.html#/resourceInfo/${id}`,
        openType: 2,
        sysId: window.localStorage.emobile_ec_id,
      });
    }

    //window.openLink(`/spa/hrm/static4mobile/index.html#/resourceInfo/${id}`);
  }

  // 基本信息
  getBase() {
    const { prefixCls, viewStore: { staticViewStore } } = this.props;
    const { staticViewBean, staticIsSimple, setStoreState } = staticViewStore;
    const userLanguage = window.e9_locale && window.e9_locale.userLanguage || 7;
    const { fromSpan = {}, senddate } = toJS(staticViewBean);
    const { imageUrl, showName, hrmId, isInternal } = fromSpan;
    const curCls = classnames(
      `${prefixCls}-base`,
      {['english']: userLanguage === 8}
    )
    return (
      <div className={curCls}>
        <Avatar url={imageUrl} name={showName} />
        <div className={`${prefixCls}-base-right`}>
          <div className={`${prefixCls}-base-right-name`} style={isInternal === 1 ? {color:'#55B1F9'}:{}}  onClick={() =>  isInternal === 1 && this.openHrmCard(hrmId)}>
            {showName}
          </div>
          <div className={`${prefixCls}-base-right-date`}>
            <span className='senddate'>{senddate}</span>
            <span className={`${prefixCls}-base-right-reciever`} onClick={() => setStoreState({ staticIsSimple: staticIsSimple ^ 1 })}>
              {staticIsSimple ?
                <span>{getLabel(83126, '精简信息')}<Icon type="arrow-up-o" size="xxs" /></span> :
                <span>{getLabel(83122, '完整信息')}<Icon type="arrow-down-o" size="xxs" /></span>
              }
            </span>
          </div>
        </div>
      </div>
    );
  }

  // 完整信息
  getComplete() {
    const { prefixCls, viewStore: { staticViewStore } } = this.props;
    const { staticViewBean = {}, staticIsSimple } = staticViewStore;
    const { id, originalMailId, isInternal, toSpan = {}, ccSpan = {}, bccSpan = {}, bccTipInfo, isShowBcc } = toJS(staticViewBean);
    if (!staticIsSimple) return null;
    return (
      staticIsSimple && <div className={`${prefixCls}-complete`}>
        <div className={`${prefixCls}-complete-to`}>
          {toSpan.list && this.getToItem(getLabel(2046, '收件人'), toSpan.list)}
          {ccSpan.list && this.getToItem(getLabel(17051, '抄送人'), ccSpan.list)}
          {isShowBcc === 1 &&
            bccTipInfo ? 
              <div className={`${prefixCls}-complete-to-item`}>
                <span className={`${prefixCls}-complete-to-item-title`}>{getLabel(81316, '密送人')}</span>
                <div className={`${prefixCls}-complete-to-item-detail`}>
                  <span className={`${prefixCls}-base-to-item-detail-tip`}>{bccTipInfo}</span>
                </div>
              </div> :
              bccSpan.list && this.getToItem(getLabel(81316, '密送人'), bccSpan.list)
          }
          {
            ((this.hasBeyondLen(toSpan.list) || this.hasBeyondLen(ccSpan.list) || this.hasBeyondLen(bccSpan.list)) || !isInternal) ? (
              <div className={`${prefixCls}-complete-unreadedcount`} onClick={this.onReadListClick}>
                {getLabel(388933, '查看全部')}
              </div>
            ) : ''
          }
        </div>
      </div>
    )
  }
  
  // 内容 （滚动区域）
  getContent() {
    const { prefixCls, viewStore: { staticViewStore } } = this.props;
    const { staticViewBean, staticMailContent, iframContent, iframContentLoading } = staticViewStore;
    const { id, fileInfos = {}, subject, isSender, recallstate,belongtoType } = toJS(staticViewBean);
    const { count } = fileInfos;
    let content = staticMailContent && this.replaceContent(staticMailContent)
    return (
      <div className={`${prefixCls}-content`}>
        {/* {iframeLoading && Toast.loading('',0)} */}
        {isSender === 0 && belongtoType =="" && recallstate === 1 ? 
          <div className={`email-noright ${prefixCls}-withdraw`}>
            <Result
              img={<Icon type="mail-withdrawal-of-mail" />}
              message={getLabel(32063, '发信方已撤回邮件')}
            />
          </div> :
          <div className={`${prefixCls}-content-flex`} id="content">
            {this.getComplete()}
            <div className={`${prefixCls}-content-container`}>
              <div className={`${prefixCls}-content-title`}>
                <span className={`${prefixCls}-content-title-subject`} dangerouslySetInnerHTML={{ __html: subject }}></span>
                {count > 0 && <span className={`${prefixCls}-content-title-icon`} onClick={this.scrollToEnclousure}><Icon type="enclosure" size="xxs" /></span>}
              </div>
            </div>
            <ContentIframe ref='content' value={content} fun={this.iframState} contentLoading={iframContentLoading} imgReg={iframContent}/>
            <div id="files">
              { this.renderFile() }
            </div>
          </div>
        }
      </div>
    )
  }

  renderFile = () => {
    const prefixCls = `${this.props.prefixCls}-files`;
    const { doFilePreview, viewStore: { staticViewStore } } = this.props;
    const { staticViewBean: { fileInfos } } = staticViewStore;
    if (!fileInfos) return null;

    const { fileList, count } = fileInfos;
    if (count === 0) return null;

    return (
      <div className={prefixCls}>
        <div className={`${prefixCls}-title`}>
          <Icon type="enclosure" size="xxs" />
          {getLabel(156, '附件')}{count}{getLabel(27591, '个')}
        </div>
        <div className={`${prefixCls}-list`}>
          <List>
            {fileList.map(file => {
              const { previewUrl, fileid, isImg, icon, iconColor } = file;
              const photoFile = isImg === 'true' ? [{
                id: file.id,
                name: file.filename,
                fileExtendName: file.fileExtendName,
                url: file.previewUrl
              }] : []
              return (
                <ListPage.Item
                  key={fileid}
                  data={file}
                  onClick={() => isImg === 'true' ? PhotoSwipe.showImage(photoFile, 0) : this.doFilePreview(file)}
                  template={{
                    default: [
                      {
                        key: 'col1',
                        style: { flex: 'none' },
                        render() {
                          if (isImg === 'true') {
                            return (
                              <img src={previewUrl} alt="" style={{ width: 30, height: 30, verticalAlign: 'middle', display: 'inline-block' }} />
                            )
                          } else {
                            return <Icon type={icon} color={iconColor} style={{ width: 30, height: 30, verticalAlign: 'middle' }} />
                          }
                        },
                      },
                      {
                        key: 'col2',
                        configs: [
                          { key: 'row1', configs: [{ key: 'filename' }] },
                          { key: 'row2', configs: [{ key: 'filesize' }] },
                        ],
                      },
                      {
                        key: 'col3',
                        render(data) {
                          return (
                            <span onClick={(event) => {
                              if (event) {
                                event.stopPropagation && event.stopPropagation();
                                event.preventDefault && event.preventDefault();
                                event.nativeEvent && event.nativeEvent.preventDefault();
                              }else if (window.event) {//针对IE
                                window.event.cancelBubble = true;
															}
															if(Tools.mobileDetect().is('iPhone')&&!Tools.mobileDetect().isEmobile()) {
                              	window.open(data.filelink+"&_ec_ismobile=true");
															} else {
                                Tools.getWeaverFile(data.filelink+"&_ec_ismobile=true", 'iframe','email');
															}
                            }}><Icon type="download" /></span>
                          );
                        },
                      },
                    ],
                  }}
                />
              );
            })}
          </List>
        </div>
      </div>
    )
  }
  
  render () {
    const { prefixCls, viewStore: { staticViewStore } } = this.props;
    const { staticViewRight, staticLoading, path, staticBaseLoading } = staticViewStore;
    const cls = classnames('wm-route-layout', prefixCls);
    let child = null;
    if (staticLoading || staticBaseLoading) {
      child = renderLoading;
    } else if (staticViewRight !== 1) {
      if(staticViewRight  === -1){
        child = (
          <div className="email-noright">
            <Result
              img={<Icon type="wuquanxian" />}
              message={getLabel(390255, '该邮件已被删除')}
            />
          </div>
        );
      } else {
        child = (
          <div className="email-noright">
            <Result
              img={<Icon type="wuquanxian" />}
              message={getLabel(385529, '无权查看该邮件')}
            />
          </div>
        );
      }
    } else {
      child = (
        <div className={`${prefixCls}-container`}>
          <div className={`${prefixCls}-flex`}>
            {this.getBase()}
            {this.getContent()}
          </div>
          <Route
            key="filePreview"
            path={`${path}/preview`}
            render={() => (<FilePreview path={`${path}/preview`} file={this.state.file} />)}
          />
          <Route
            key="readList"
            path={`${path}/readList`}
            render={() => (<StaticReadList path={`${path}/readList`}/>)}
          />
        </div>
      );
    }
    return (
      <RouteLayout>
        <div key="static-view" className={cls}>{child}</div>
      </RouteLayout>
    )
  }
}

export default StaticView